<?php

namespace App\Services\Admin;

use App\Exceptions\LogicException;
use App\Models\AdminRole;
use App\Models\Admins;
use App\Models\Permission;
use App\Models\Role;
use App\Models\RolePermission;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AuthService
{
    protected $adminRoleModel;
    protected $permissionModel;
    protected $rolePermissionModel;
    protected $adminsModel;

    public function __construct(AdminRole $adminRoleModel, Permission $permissionModel, RolePermission $rolePermissionModel, Admins $adminsModel)
    {
        $this->adminRoleModel = $adminRoleModel;
        $this->permissionModel = $permissionModel;
        $this->rolePermissionModel = $rolePermissionModel;
        $this->adminsModel = $adminsModel;
    }

    public function login(array $credentials)
    {
        if (!($token = Auth::guard('admin')->attempt($credentials))) {
            throw new LogicException('Invalid account or password');
        }

        return [
            'token' => $token,
            'expires_in' => auth('admin')->factory()->getTTL() * 60,
        ];
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        Auth::guard('admin')->logout();
    }

    /**
     * 刷新token
     */
    public function refresh()
    {
        return [
            'token' => Auth::guard('admin')->refresh(),
            'token_type' => 'bearer',
            'expires_in' => auth('admin')->factory()->getTTL() * 60
        ];
    }

    /**
     * 获取当前用户信息
     */
    public function me()
    {
        $user = Auth::guard('admin')->user();
        if (!$user) {
            throw new LogicException('Invalid token', 401);
        }

        $permissionCodes = $this->getUserPermissions($user->id);

        return [
            'id' => $user->id,
            'username' => $user->username,
            'email' => $user->email,
            'avatar' => $user->avatar,
            'permissions' => $permissionCodes
        ];
    }

    /**
     * 获取用户权限
     * @param int $adminId
     * @return array
     */
    public function getUserPermissions(int $adminId)
    {
        // 获取用户角色
        $roles = $this->adminRoleModel->getAdminRoles($adminId);
        $roleIds = array_column($roles, 'id');

        $permissions = $permissionCodes = [];
        // 判断是否为超级管理员
        if (in_array(Role::SUPER_ROLE_ID, $roleIds)) {
            // 超级管理员拥有所有权限
            $permissions = $this->permissionModel->search([], ['slug', 'module']);
        } else if ($roleIds) {
            // 普通用户根据角色获取权限
            $permissions = $this->rolePermissionModel->getAdminPermissionsByRoleIds($roleIds);
        }
        if (!empty($permissions)) {
            foreach ($permissions as $permission) {
                $permissionCodes[] = $permission['module'] . '.' . $permission['slug'];
            }
        }
        return $permissionCodes;
    }

    /**
     * 修改密码
     * @param int $adminId
     * @param array $data
     * @return array
     * @throws LogicException
     */
    public function changePassword(int $adminId, array $data): array
    {
        $user = $this->adminsModel->take(['id' => $adminId], ['id', 'password', 'token_version']);
        if (!$user) {
            throw new LogicException('用户不存在');
        }

        if (!Hash::check($data['old_password'], $user['password'])) {
            throw new LogicException('原密码不正确');
        }

        $password = Hash::make($data['new_password']);
        $updateData = [
            'password' => $password,
            'token_version' => $user['token_version'] + 1
        ];
        $rows = $this->adminsModel->modify($adminId, $updateData);

        return ['affected_rows' => $rows];
    }
}
